package drive.RemakeService.ServiceFormat;

import com.aliyuncs.exceptions.ClientException;
import com.google.gson.*;
import drive.Mapper.*;
import drive.Model.*;

import drive.RemakeService.ServiceInterface.TravelNoteService;
import drive.pojo.AliyunOSSOperator;
import drive.pojo.JwtUtils;
import drive.pojo.NetWork;
import okhttp3.*;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
public class TravelNoteServiceA implements TravelNoteService {


    @Value("${official.account.id}")
    private int OFFICIAL_ACCOUNT_ID; // 官方账号ID，从配置文件中获取

    Gson gson = new Gson();

    @Autowired
    NetWork netWork;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private ReportRecordMapper reportRecordMapper;

    @Autowired
    private FollowRelationMapper followRelationMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private FavoriteRecordMapper favoriteRecordMapper;

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @Override
    @Transactional
    public String publishTravelNote(Article article, List<String> img_url) throws JSONException, IOException {
        // 实现文章发布逻辑
        String tag = netWork.getKeyWord(article.getTitle(),article.getContent());
        article.setTag(tag);
        article.setCreationTime(new Date());
        articleMapper.add(article);
        int articleID = article.getArticleID();
        String[] img = img_url.toArray(new String[0]);
        for (int i = 0; i < img.length; i++) {
            Image image = new Image();
            image.setImageUrl(img[i]);
            image.setArticleID(articleID);
            image.setIndexNo(i);
            image.setUploadTime(new Date());
            image.setImgType(Image.Status.article);
            imageMapper.add(image);
        }
        return "游记发布成功";
    }

    @Override
    public String browseTravelNotes(int articleID) {
        // 实现文章浏览逻辑
        Article article = articleMapper.findById(articleID);
        articleMapper.update_re(article);
        return gson.toJson(article);
    }

    @Override
    public String searchTravelNotes(String keyword, int PageNum, int PageSize) {
        // 实现文章搜索逻辑
        int offset = (PageNum-1)*PageSize;

        List<Article> list = articleMapper.findPaginatedByKeyword(keyword,offset,PageSize);
        return gson.toJson(list);
    }

    @Override
    public String reportTravelNote(String token, int articleID, String reason) {
        // 实现文章举报逻辑
        int userID = JwtUtils.getuserID(token);
        ReportRecord reportRecord = new ReportRecord();
        reportRecord.setReporterID(userID);
        reportRecord.setReporteeID(articleID);
        reportRecord.setReportType(ReportRecord.ReportType.article);
        reportRecord.setReportReason(reason);
        reportRecord.setSubmissionTime(new Date());
        reportRecord.setReportStatus(ReportRecord.Status.pending);
        reportRecordMapper.add(reportRecord);
        //添加redis防止短时间内重复举报
        return "游记举报成功";
    }

    @Override
    @Transactional
    public String followTravelNoteAuthor(String token,Integer authorID) {
        // 实现关注作者逻辑
        int userID = JwtUtils.getuserID(token);
        FollowRelation followRelation = new FollowRelation();
        followRelation.setFollowerID(userID);
        followRelation.setFollowedID(authorID);
        followRelation.setCreateTime(new Date());
        followRelationMapper.add(followRelation);
        User user = userMapper.selectUserById(userID);
        sendOfficialMessage(authorID,user.getUsername()+",关注了你");
        return "关注游记作者成功";
    }


    @Override
    @Transactional
    public String commentTravelNote(String token,Integer articleID, String comment, int parentCommentID) {
        // 实现文章评论逻辑
        int userID = JwtUtils.getuserID(token);
        Comment com = new Comment();
        com.setArticleID(articleID);
        com.setUserID(userID);
        com.setContent(comment);
        com.setCreationTime(new Date());
        if(parentCommentID==0){
            commentMapper.add_top(com);
            Article article = articleMapper.findById(articleID);
            User user = userMapper.selectUserById(userID);
            sendOfficialMessage(article.getAuthorID(),"用户ID:"+ user.getUserID() +",评论了我的文章,"+"评论ID:"+com.getCommentID());
        }else{
            com.setParentCommentID(parentCommentID);
            commentMapper.add(com);
            Comment c = commentMapper.findByCommentID(com.getParentCommentID());
            User user = userMapper.selectUserById(userID);
            sendOfficialMessage(c.getUserID(),"用户ID:"+ user.getUserID() +",回复了你的评论,"+"评论ID:"+com.getCommentID());
        }
        articleMapper.updateArticleCommentCountByArticleID(articleID);
        return "游记评论成功";
    }

    @Override
    @Transactional
    public String collectTravelNote(String token, int articleID) {
        // 实现文章收藏逻辑
        int userID = JwtUtils.getuserID(token);
        FavoriteRecord favoriteRecord = new FavoriteRecord();
        favoriteRecord.setUserID(userID);
        favoriteRecord.setContentID(articleID);
        favoriteRecord.setContentType(FavoriteRecord.Status.article);
        favoriteRecord.setCreationTime(new Date());
        favoriteRecordMapper.add(favoriteRecord);
        Article article = articleMapper.findById(articleID);
        User user = userMapper.selectUserById(userID);
        sendOfficialMessage(article.getAuthorID(),user.getUsername() +",收藏了我的文章");

        //修改收藏数量
        articleMapper.updateArticleFavoriteCountByArticleID(articleID);
        return "游记收藏成功";
    }

    @Override
    public String getFirstImageByarticleID(int articleID) {
        Image image = imageMapper.getFirstImageByItemID(articleID,"article");
        if (image == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该文章没有图片\"}");
        }
        return gson.toJson(image);
    }

    @Override
    public String getImageByarticleID(int articleID) {
        List<Image> image = imageMapper.getImageByItemID(articleID,"article");
        if (image == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该文章没有图片\"}");
        }
        return gson.toJson(image);
    }

    private void sendOfficialMessage(int authorId, String messageContent) {
        ChatSession chatSession = chatSessionMapper.findByUserIDs(OFFICIAL_ACCOUNT_ID,authorId);
        if (chatSession == null) {
            // 创建会话
            chatSession = new ChatSession();
            chatSession.setUser1ID(OFFICIAL_ACCOUNT_ID);
            chatSession.setUser2ID(authorId);
            chatSession.setCreationTime(new Date());
            chatSessionMapper.add(chatSession);
            System.out.println(chatSession);
        }
        System.out.println("发送关注消息中");
        // 发送消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatSessionID(chatSession.getChatSessionID());
        chatMessage.setSenderID(OFFICIAL_ACCOUNT_ID);
        chatMessage.setContent(messageContent);
        chatMessage.setSendTime(new Date());
        chatMessage.setStatus(ChatMessage.Status.sending);
        chatMessageMapper.add(chatMessage);

        chatSessionMapper.update_time(chatSession.getChatSessionID());
    }

    @Override
    public String getFirstImageByArticleID(int articleID) {
        Image image = imageMapper.getFirstImageByItemID(articleID,"article");
        if (image == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该文章没有图片\"}");
        }
        return gson.toJson(image);
    }

    @Override
    public String getImageByArticleID(int articleID) {
        List<Image> image = imageMapper.getImageByItemID(articleID,"article");
        if (image == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"该文章没有图片\"}");
        }
        return gson.toJson(image);
    }

    /**
     * 删除评论
     * @param commentID 评论ID
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String deleteComment(int commentID) {
        Comment comment = commentMapper.findByCommentID(commentID);
        if (comment == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"评论不存在\"}");
        }
        commentMapper.delete_son_comment(commentID);
        commentMapper.delete(commentID);
        articleMapper.updateArticleCommentCountByArticleID(comment.getArticleID());
        return gson.toJson("{\"status\":\"success\",\"message\":\"评论删除成功\"}");
    }

    /**
     * 取消收藏
     * @param favoriteID 收藏记录ID
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String deleteFavorite(int favoriteID) {
        FavoriteRecord favoriteRecord = favoriteRecordMapper.findByFavoriteID(favoriteID);
        int result = favoriteRecordMapper.delete(favoriteID);
        if (result > 0) {
            articleMapper.updateArticleFavoriteCountByArticleID(favoriteRecord.getContentID());
            return gson.toJson("{\"status\":\"success\",\"message\":\"取消收藏成功\"}");
        } else {
            return gson.toJson("{\"status\":\"error\",\"message\":\"收藏记录不存在\"}");
        }
    }

    /**
     * 根据用户ID和文章ID获取收藏ID
     * @param userID 用户ID
     * @param articleID 文章ID
     * @return 包含收藏ID的JSON字符串
     */
    @Override
    public String getFavoriteIdByUserAndArticle(int userID, int articleID) {
        FavoriteRecord favoriteRecord = favoriteRecordMapper.findByUserAndArticle(userID, articleID);
        if (favoriteRecord == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"收藏记录不存在\"}");
        }
        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"favoriteID\":" + favoriteRecord.getFavoriteID()
                + "}");
    }

    @Override
    public String image_back(String imageUrl,String originalFilename) throws IOException, ClientException {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("url", imageUrl)
                .build();

//        Request request = new Request.Builder()
//                .url("http://localhost:5000/predict ")
//                .post(formBody)
//                .build();
        //服务器版本
        Request request = new Request.Builder()
                .url("http://113.44.3.120:8080/predict")
                .post(formBody)
                .build();


        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code());
            }
            String res = response.body().string(); // 获取完整 JSON 响应
//            System.out.println(res);
            JsonObject json = JsonParser.parseString(res).getAsJsonObject();
            String base64Data = json.get("image").getAsString(); // 假设字段名为 "image"
            // 解析 "hazard_name" 字段（嵌套的 JSON 数组）
            JsonArray hazardNameArray = json.getAsJsonArray("hazard_name");
            List<Map<String, Object>> hazardNameList = new ArrayList<>();

            for (JsonElement element : hazardNameArray) {
                if (element.isJsonObject()) {
                    JsonObject hazardObj = element.getAsJsonObject();
                    Map<String, Object> hazardMap = new HashMap<>();
                    hazardMap.put("class", hazardObj.get("class").getAsString());
                    hazardMap.put("confidence", hazardObj.get("confidence").getAsDouble());
                    hazardNameList.add(hazardMap);
                }
            }

            // 打印结果
            System.out.println("Image Base64 Data: " + base64Data);
            System.out.println("Hazard Name List: " + hazardNameList);
            // 解码 Base64 数据
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);

            // 生成唯一文件名

            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            System.out.println(uniqueFileName);
            // 上传文件
            String url = aliyunOSSOperator.upload(imageBytes, uniqueFileName);
            Map<String,Object> result = new HashMap<>();
            result.put("image",url);
            result.put("hazard_name",hazardNameList);
            return gson.toJson(result);
        }
    }

}
